package in.hitmedia.test.sort;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SelectionSort 
{

	private Long[] read(String filename) throws IOException
	{
		
		BufferedReader br = new BufferedReader(new FileReader(filename));
		
		String line = null;
		
		List<Long> a = new ArrayList<Long>();
		while((line = br.readLine()) != null)
		{
			try
			{
				long parseLong = Long.parseLong(line.trim());
				a.add(parseLong);
			}
			catch (NumberFormatException nfe)
			{
				
			}
		}
		
		return a.toArray(new Long[a.size()]); 
	}
	
	
	
	private void selectionSort(Long a[])
	{
		for (int i=0; i < a.length-1; ++i)
		{
			int min=i;
			for (int j=i+1; j < a.length; ++j)
			{
				if (a[j] < a[min])
				{
					min=j;
				}
			}
			
			if (min != i)
			{
				long tmp=a[i];
				a[i]=a[min];
				a[min]=a[i];
			}
		}
		
	}
	
	private static void print(Long a[])
	{
		for(int i=0; i < a.length; ++i)
		{
			System.out.print(a[i]+"\t");
			if ((i+1) %10 == 0)
			{
				System.out.println();
			}
		}
		System.out.println();
	}
	
	public void runSelectionSort (String in, String out)
	{
		try
		{
			Long[] inArray = read(in);
			//print(inArray);
			
			long start = System.currentTimeMillis();
			selectionSort(inArray);
			long end = System.currentTimeMillis();
			
			System.out.println("Time to process "+((end - start)) +" miliseconds.");
			
			BufferedWriter bw = new BufferedWriter(new FileWriter(out));
			
			for (int i = 0; i < inArray.length; ++i)
			{
				bw.write(""+inArray[i]);
				bw.newLine();
			}
			bw.close();
			
			//print(inArray);
		}
		catch (Exception e)
		{
			System.out.println("Received exception"+ e);
		}
		
		
	}
	
	public static void main(String args[])
	{
		SelectionSort is = new SelectionSort();
		is.runSelectionSort(args[0], args[1]);
	}
	
}
